package com.lml.gpt;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author luomingliang
 * @date 2023/3/6 20:00
 */
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;

public class SHA256WithSaltExample {
    public static final int SALT_LENGTH_BYTES = 16; //盐值长度，单位是字节

    public static void main(String[] args) {
        String originalString = "Hello World!";
        String salt = generateSalt(SALT_LENGTH_BYTES); //生成盐值
        String hashedString = getSHA256HashWithSalt(originalString + salt); //将盐值与原始数据连接后生成SHA-256哈希值
        System.out.println("Salt: " + salt);
        System.out.println("SHA-256 Hash of \"" + originalString + "\" with Salt is: " + hashedString);
    }

    public static String generateSalt(int saltLength) { //生成盐值
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[saltLength]; //生成指定长度的字节数组
        random.nextBytes(salt); //填充字节数组
        return bytesToHex(salt); //将字组转换为十六进制字符串
    }

    public static String getSHA256HashWithSalt(String input) { //获取SHA-256哈希值
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] encodedHash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            StringBuilder hexString = new StringBuilder();
            for (byte b : encodedHash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private static String bytesToHex(byte[] bytes) { //将字节数组转换为十六进制字符串
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

